package com.algorithm.one2fifty;

import java.util.HashMap;
import java.util.Map;

/**
 * @author tuzhijin
 */
public class RomanToInt_13 {

    /**
     * 初始化值
     */
    static Map<Character, Integer> param = new HashMap<Character, Integer>(16){{
        param.put('I', 1);
        param.put('V', 5);
        param.put('X', 10);
        param.put('L', 50);
        param.put('C', 100);
        param.put('D', 500);
        param.put('M', 1000);
    }};

    public static void main(String[] args) {
        System.out.println(romanToInt("IV"));
    }

    public static Integer romanToInt(String s) {
        int result = 0;
        int length = s.length();
        for (int i = 0; i < length; i++) {
            Integer value = param.get(s.charAt(i));
            // 罗马数字中小的数字在大的数字的右边，此情况相加，反之相减
            // i<length-1此判断是防止数组角标越界
            if (i < length - 1 && value < param.get(s.charAt(i + 1))) {
                result = result - value;
            } else {
                result = result + value;
            }
        }
        return result;
    }
}
